package com.mapler.autoresponder.ui;

import com.mapler.autoresponder.service.AutoResponderWorker;
import com.mapler.model.AdModel;
import com.mapler.model.SModel;
import com.mapler.model.UAModel;
import com.mapler.service.INotifier;
import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

/**
 *
 * @author none
 */
public class EngineAutoResponderPostUI extends javax.swing.JPanel implements INotifier {

    public ScheduledExecutorService emailExecutor = Executors.newScheduledThreadPool(10);
    protected ScheduledFuture<?> emailFuture = null;
    private String username;
    private String password;
    private String country;
    private SModel sModel;
    private ArrayList<UAModel> uaModels;
    private ArrayList<AdModel> addModels;
    private HashMap<String, UAModel> usHashMap;
    private static Logger log = Logger.getLogger(EngineAutoResponderPostUI.class);
    private INotifier iNotifier;
    private AutoResponderWorker autoResponderWorker;

    public EngineAutoResponderPostUI(String username, String password, String country) {
        this.username = username;
        this.password = password;
        this.country = country;
        initComponents();
        this.vpn.setSelected(true);
        initSettings();
    }

    public SModel getsModel() {
        if (sModel == null) {
            sModel = new SModel();
        }
        return sModel;
    }

    public void setsModel(SModel sModel) {
        this.sModel = sModel;
    }

    public ArrayList<UAModel> getUaModels() {
        if (uaModels == null) {
            uaModels = new ArrayList<UAModel>();
        }
        return uaModels;
    }

    public void setUaModels(ArrayList<UAModel> uaModels) {
        this.uaModels = uaModels;
    }

    public ArrayList<AdModel> getAddModels() {
        if (addModels == null) {
            addModels = new ArrayList<AdModel>();
        }
        return addModels;
    }

    public void setAddModels(ArrayList<AdModel> addModels) {
        this.addModels = addModels;
    }

    public HashMap<String, UAModel> getUsHashMap() {
        if (usHashMap == null) {
            usHashMap = new HashMap<String, UAModel>();
        }
        return usHashMap;
    }

    public void setUsHashMap(HashMap<String, UAModel> usHashMap) {
        this.usHashMap = usHashMap;
    }

    /**
     * Creates new form EngineUI
     */
    public EngineAutoResponderPostUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        start = new javax.swing.JButton();
        end = new javax.swing.JButton();
        vpn = new javax.swing.JCheckBox();
        message = new javax.swing.JLabel();
        jTFProxy = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        vpnusername = new javax.swing.JTextField();
        vpnpassword = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTFPostPerIP = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jFPostPerAccount = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jBStop = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jCBRandom = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();

        jLabel4.setText("jLabel4");

        start.setText("Start");
        start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startActionPerformed(evt);
            }
        });

        end.setText("Stop & Exit");
        end.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                endActionPerformed(evt);
            }
        });

        vpn.setText("VPN");

        jLabel2.setText("Proxy");

        jLabel5.setText("Username");

        jLabel6.setText("Password");

        jTFPostPerIP.setToolTipText("");

        jLabel7.setText("Change IP");

        jLabel1.setText("Change SMTP");

        jBStop.setText("Stop");
        jBStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBStopActionPerformed(evt);
            }
        });

        jLabel9.setText("AutoResponder");

        jCBRandom.setText("Random post selection");

        jCheckBox2.setText("Store & Send");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addComponent(jLabel8)
                .addGap(416, 416, 416))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(message, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(31, 31, 31))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel7)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jTFPostPerIP, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jFPostPerAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGap(121, 121, 121))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel2)
                                .addComponent(jLabel5)
                                .addComponent(jLabel6))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(vpn)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(vpnpassword, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(vpnusername, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTFProxy, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(70, 70, 70)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jCheckBox2)
                                .addComponent(jCBRandom))))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(163, 163, 163)
                            .addComponent(start)
                            .addGap(12, 12, 12)
                            .addComponent(jBStop)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(end))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jLabel9))))
                .addContainerGap(193, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(50, 50, 50)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFProxy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vpnusername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vpnpassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(vpn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFPostPerIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jFPostPerAccount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCBRandom)
                .addGap(5, 5, 5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBox2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(start)
                    .addComponent(end)
                    .addComponent(jBStop))
                .addGap(29, 29, 29))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startActionPerformed
        if (this.getUaModels() == null || this.getUaModels().isEmpty()) {
            notify("Account is empty");
            return;
        }
        
        if (this.getAddModels()== null || this.getAddModels().isEmpty()) {
            notify("Posting info is empty");
            return;
        }
        
        this.getsModel().setIsVPN(vpn.isSelected());
        this.getsModel().setProxy(jTFProxy.getText());
        this.getsModel().setName(this.vpnusername.getText());
        this.getsModel().setPass(this.vpnpassword.getText());
        this.getsModel().setPostPerIP(this.jTFPostPerIP.getText());
        this.getsModel().setRandom(jCBRandom.isSelected());
        this.getsModel().setStopEngine(false);
        int postPerAcc = 1;
        if (!this.jFPostPerAccount.getText().isEmpty()) {
            postPerAcc = Integer.parseInt(this.jFPostPerAccount.getText());
        }
        this.getsModel().setPostPerAccout(postPerAcc);

        sModel.setMaxWaitTime(IConstant.MAXWAITTIME.toString());
        if (jTFPostPerIP.getText() != null && !jTFPostPerIP.getText().isEmpty()) {
            sModel.setMaxWaitTime(jTFPostPerIP.getText());
        }

        sModel.setUsername(username);
        sModel.setPassword(password);
        sModel.setCountry(country);

        autoResponderWorker = new AutoResponderWorker(this.getiNotifier(), this.getsModel(), this.getUaModels(),this.getAddModels());
        autoResponderWorker.update();
    }//GEN-LAST:event_startActionPerformed

    private void endActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endActionPerformed
        try {
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=autoresponderUser/logout&username=" + this.username + "&password=" + this.password;
            String response = HttpHelper.post(new URL(uri), "");

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            if (errorCode.equalsIgnoreCase("000")) {
                String msg = document.valueOf("Response/message");
                log.debug("Problem in logout. causes " + msg);
            } else {
                log.debug("Signout perfectly ");
            }
            Runtime.getRuntime().exec("taskkill /F /IM java.exe");
        } catch (Throwable ex) {
            log.debug("Error " + ex);
        }

    }//GEN-LAST:event_endActionPerformed

    private void jBStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBStopActionPerformed
        this.getsModel().setStopEngine(true);
    }//GEN-LAST:event_jBStopActionPerformed

    public void initSettings() {
        this.setsModel(null);
        this.setUaModels(null);
        this.setAddModels(null);
        this.setUsHashMap(null);
    }
    
    private void fillUserAccount(ArrayList<UAModel> uaModels) {
        try {
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=autoresponderAccount/getPostAccounts&username="
                    + this.username + "&password=" + this.password + "&working=0";
            String response = HttpHelper.post(new URL(uri), "");
            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            if (!errorCode.equalsIgnoreCase("000")) {
                List<Node> list = document.selectNodes("/Response/accounts/account");
                for (Node node : list) {
                    UAModel model = new UAModel();
                    model.setId(node.valueOf("id"));
                    model.setServer(node.valueOf("server"));
                    model.setPort(node.valueOf("port"));
                    model.setSsl(node.valueOf("ssl"));
                    model.setUsername(node.valueOf("username"));
                    model.setPassword(node.valueOf("password"));
                    model.setReplyEmail(node.valueOf("reply_email"));
                    model.setWorking(node.valueOf("working"));
                    uaModels.add(model);
                }
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
            
    private void fillPostInfo(ArrayList<AdModel> adModels) {
        try {
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=AutoResponderPostinfo/getAccounts&username="
                    + this.username + "&password=" + this.password+ "&working="+1;
            String response = HttpHelper.post(new URL(uri), "");
            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            if (!errorCode.equalsIgnoreCase("000")) {
                List<Node> list = document.selectNodes("/Response/accounts/account");
                for (Node node : list) {
                    AdModel model = new AdModel();
                    model.setId(node.valueOf("id"));
                    model.setTitle(node.valueOf("uri"));
                    model.setDescription(node.valueOf("udvalue1"));
                    adModels.add(model);
                }
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton end;
    private javax.swing.JButton jBStop;
    private javax.swing.JCheckBox jCBRandom;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JTextField jFPostPerAccount;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField jTFPostPerIP;
    private javax.swing.JTextField jTFProxy;
    private javax.swing.JLabel message;
    private javax.swing.JButton start;
    private javax.swing.JCheckBox vpn;
    private javax.swing.JTextField vpnpassword;
    private javax.swing.JTextField vpnusername;
    // End of variables declaration//GEN-END:variables

    @Override
    public void notify(final String info) {
        try {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    message.setText(info);
                    log.debug(info);
                }
            });
        } catch (Throwable ex) {
            log.debug("notify:: Error causes " + ex.getMessage());
        }
    }

    public INotifier getiNotifier() {
        if (iNotifier == null) {
            iNotifier = this;
        }
        return iNotifier;
    }

    public void setiNotifier(INotifier iNotifier) {
        this.iNotifier = iNotifier;
    }

    @Override
    public void write(String info) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
